<template>
  <div>
    <h2>结算</h2>
    <p>总金额：￥{{ total.toFixed(2) }}</p>
    <p v-if="coupons.length">
      可用优惠券：
      <span v-for="c in coupons" :key="c.couponId">-￥{{ c.discountAmount }}</span>
    </p>
    <button @click="onSubmit" :disabled="submitting || total === 0">确认结算</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCart, submitOrder } from '@/utils/cart'
import { getAvailableCoupons, startPayment } from '@/utils/payment'

const total = ref(0)
const coupons = ref([])
const submitting = ref(false)
const router = useRouter()

// ① 在挂载时取购物车，计算初始总金额
async function fetchInitialTotal() {
  try {
    const res = await getCart()
    if (res.data.code === 0) {
      const items = res.data.data
      total.value = items.reduce((sum, i) => sum + (i.price || 0) * i.quantity, 0)
    }
  } catch (e) {
    console.error('拉取购物车失败', e)
  }
}

async function onSubmit() {
  submitting.value = true
  try {
    // ② 结算请求
    const orderRes = await submitOrder()
    if (orderRes.data.code !== 0) {
      throw new Error('结算失败')
    }
    const { orderId, totalAmount } = orderRes.data.data
    total.value = totalAmount

    // ③ 拉优惠券
    const couponRes = await getAvailableCoupons(orderId)
    if (couponRes.data.code === 0) {
      coupons.value = couponRes.data.data.coupons
    }

    // ④ 发起支付
    const payRes = await startPayment(orderId)
    if (payRes.data.code === 0) {
      window.open(payRes.data.data.paymentUrl, '_blank')
      await router.push('/')  // 支付后返回首页
    } else {
      throw new Error('支付失败')
    }
  } catch (err) {
    console.error('结算流程出错', err)
    alert(err.message || '流程出错')
  } finally {
    submitting.value = false
  }
}

onMounted(fetchInitialTotal)
</script>
